package com.bidevalution.business.function;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.mvel2.MVEL;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import com.bidevalution.support.util.LogUtil;
import com.bidevalution.support.util.OConvertUtil;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.googlecode.aviator.AviatorEvaluator;
import com.qtp.core.redis.RedisUtil;

public class FunctionCalculator {
	private static Logger logUtil = Logger.getLogger(FunctionCalculator.class);
	public static String computeAviator(String formularConfig,Map<String, Object> env) {
		logUtil.info(env);
		if(StringUtils.isEmpty(formularConfig)) {
			return null;
		}
		String result =  StringUtil.toString(AviatorEvaluator.execute(removeSqlConfig(formularConfig), env));
		logUtil.info("计算结果:"+result+":公式:"+formularConfig);
		return result;
	}
	public static String computeMVEL(String formularConfig,Map<String, Object> env) {
		env.put("OConvertUtil", new OConvertUtil());
		logUtil.info(env);
		if(StringUtils.isEmpty(formularConfig)) {
			return null;
		}
		String result = StringUtil.toString(MVEL.eval(removeSqlConfig(formularConfig), env));
		logUtil.info("计算结果:"+result+":公式:"+formularConfig);
		return result;
	}
	public static String removeSqlConfig(String formularConfig) {
		if(formularConfig.contains("{sql[")) {
			int startIndex = formularConfig.indexOf("{sql[");
			int endIndex = formularConfig.indexOf("]}");
			String sql = formularConfig.substring(startIndex+5,endIndex);
			String sqlKey = DigestUtils.md5DigestAsHex(sql.getBytes());
			RedisUtil.set(sqlKey, sql);
			RedisUtil.expire(sqlKey, 120);//两分钟
			formularConfig = formularConfig.substring(0,startIndex)+"'"+sqlKey+"'"+formularConfig.substring(endIndex+2);
			return removeSqlConfig(formularConfig);
		}else {
			return formularConfig;
		}

	}
	public static void main(String[] args) {
		//System.out.println(removeSqlConfig("sqlExecutor($sql[select count(1) from be_evalution_expert where section_step_code='15' and section_id='{sectionId}' and is_del='0'],'COUNT')>5?average(removeLimitList(sqlExecutor($sql[select price from be_section_enterprise where section_id='{sectionId}'],'ARRAY'),average(removeList(sortList(sqlExecutor($sql[select price from be_section_enterprise where section_id='{sectionId}'],'ARRAY'),0),round(sqlExecutor($sql[select count(1) from be_section_enterprise where section_id='{sectionId}'],'COUNT')*0.1),round(sqlExecutor($sql[select count(1) from be_section_enterprise where section_id='{sectionId}'],'COUNT')*0.1))),'lt')):0"));;
//		String aa = "1>2?'1':'2'";
//		Map<String, Object> paramMap = new HashMap<String, Object>();
//		paramMap.put("$basicPrice", 4);
//		paramMap.put("$sectionStepId", "aaaa");
//		paramMap.put("$expertId", "bbb");
//		paramMap.put("$sectionId", "dddd");
//		String expression = "if ($basicPrice > 0) {return \"SELECT\r\n" + 
//				"	a.enterprise_id enterpriseId,a.enterprise_name enterpriseName,\r\n" + 
//				"	{basePrice} as c1,a.price as c2,\r\n" + 
//				"	abs(price-basicPrice) as c3,IFNULL(c4,1) c4\r\n" + 
//				"	from be_section_enterprise a left join (\r\n" + 
//				"	SELECT\r\n" + 
//				"		enterprise_id,\r\n" + 
//				"		MAX(CASE column_code WHEN 'c4' THEN column_value END) AS c4\r\n" + 
//				"	\r\n" + 
//				"	FROM\r\n" + 
//				"		be_evalution_expert\r\n" + 
//				"	WHERE\r\n" + 
//				"			section_step_id = '{sectionStepId}'\r\n" + 
//				"		AND expert_id = '{expertId}' AND is_del='0'\r\n" + 
//				"		GROUP BY enterprise_id)b on a.enterprise_id= b.enterprise_id where a.section_id='sectionId' and  a.price>={basicPrice} order by price asc limit 5\"; } else if ($basicPrice== -1) { return \"Minus one!\"; } else { return \"Something else!\"; }";
		AviatorEvaluator.addFunction(new TestFunction(null));
		//String expression = "5>$basicPrice?'1':'2'";
		//Object object = computeAviator(expression, paramMap);
		List<Map<String, Object>> dataList = Lists.newArrayList();
		Map<String, Object> map = Maps.newHashMap();
		map.put("hh",1);
		map.put("gg",2);
		map.put("c2",0);
		dataList.add(map);
		map = Maps.newHashMap();
		map.put("hh",2);
		map.put("gg",2);
		map.put("c2",0);
		dataList.add(map);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("tbbjdf","22");
		dataMap.put("tbbj","22");
		dataMap.put("basicPrice","22");
		dataMap.put("list",dataList);
		dataMap.put("OConvertUtil",new OConvertUtil());
		//ColumnHeader columnHeader = new ColumnHeader("LINENUMBER", "序号", "LINENUMBER", "", "", "", "0", "", "");
		//dataMap.put("columnHeader", columnHeader);
//		String functionString = "function setPermission(columnHeader){ if(JSWeight==null || JSWeight =='' || JSWeight =='0'){columnHeaderMap['inputType']='HIDDEN';}} setPermission(columnHeaderMap)";
//		System.out.println(computeMVEL(functionString, dataMap)); // Greater than zero!
//		System.out.println(dataMap.get("columnHeaderMap"));
		AviatorEvaluator.addFunction(new TestFunction(null));
		//System.out.println(computeMVEL("var total = list.size;foreach(item : list) {if item['fwz']<$PARAM_BillDeviateRateLower{kf=4/total}};System.out.println(list.size);", dataMap)+"##$$$$$$$$$");

		System.out.println(computeAviator("basicPrice=double(tbbj)-double(tbbjdf)", dataMap));
		//computeMVEL("c6=555;OConvertUtil.setScale(2/3,2)", dataMap);
		System.out.println(dataMap);

//		final List<String> list = new ArrayList<String>();
//	    list.add("hello");
		
//	    list.add(" world");
//	    final int[] array = new int[3];
//	    array[0] = 0;
//	    array[1] = 1;
//	    array[2] = 3;
//	    final Map<String, Date> map = new HashMap<String, Date>();
//	    map.put("date", new Date());
//	    Map<String, Object> env = new HashMap<String, Object>();
//	    env.put("list", list);
//	    env.put("array", array);
//	    env.put("mmap", map);
//	    System.out.println(AviatorEvaluator.execute("list[0]+list[1]", env));   // hello world
//	    System.out.println(AviatorEvaluator.execute("'array[0]+array[1]+array[2]=' + (array[0]+array[1]+array[2])", env));  // array[0]+array[1]+array[2]=4
//	    System.out.println(AviatorEvaluator.execute("'today is ' + mmap.date ", env));  // today is Wed Feb 24 17:31:45 CST 2016
	}
}
